package com.jy.oms.framework.asyn.task.collector;

import com.jy.oms.framework.asyn.task.constants.CacheConstants;
import com.jy.oms.framework.asyn.task.core.RedissonClientProxy;
import com.jy.oms.framework.asyn.task.executor.ITaskLifecycleListener;
import com.jy.oms.framework.asyn.task.model.TaskWrapper;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 任务执行状态收集器
 *
 * @author liuquan
 */
@Service
public class TaskRunningStateCollector implements ITaskLifecycleListener {

    /**
     * 任务执行完时清除任务标记
     */
    @Override
    public void onFinish(TaskWrapper taskWrapper) {
        this.clear(taskWrapper.getParamIdentifier());
    }

    private void clear(String key) {
        if (key == null) {
            return;
        }

        String cacheKey = CacheConstants.genCacheKey(CacheConstants.TASK_EXECUTED_CHECKER, key);
        RedissonClient redissonClient = RedissonClientProxy.getRedissonClient();
        RBucket<Boolean> bucket = redissonClient.getBucket(cacheKey);
        bucket.delete();
    }

    /**
     * 判断任务是否能执行
     */
    public boolean canExecute(String key) {
        String cacheKey = CacheConstants.genCacheKey(CacheConstants.TASK_EXECUTED_CHECKER, key);
        RedissonClient redissonClient = RedissonClientProxy.getRedissonClient();
        RBucket<Boolean> bucket = redissonClient.getBucket(cacheKey);
        boolean check = bucket.compareAndSet(null, true);
        if (check) {
            bucket.expire(1, TimeUnit.HOURS);
        }
        return check;
    }

}
